<?php
// 错误报告设置
error_reporting(E_ALL);
ini_set('display_errors', 1);

// 数据库配置
define('DB_CONFIG', [
    'host' => 'localhost',
    'username' => 'root',
    'password' => 'root',
    'database' => 'nuochefuwu',
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci'
]);

// 系统配置
define('SYSTEM_CONFIG', [
    'notification_retention_days' => 30,  // 通知记录保留天数
    'max_message_length' => 500,         // 最大消息长度
    'min_cooldown' => 30000,            // 最小冷却时间（毫秒）
    'max_cooldown' => 300000            // 最大冷却时间（毫秒）
]);

/**
 * 数据库连接函数
 * @return mysqli 数据库连接对象
 * @throws Exception 连接失败时抛出异常
 */
function connectDB() {
    try {
        $conn = new mysqli(
            DB_CONFIG['host'],
            DB_CONFIG['username'],
            DB_CONFIG['password'],
            DB_CONFIG['database']
        );
        
        if ($conn->connect_error) {
            throw new Exception("数据库连接失败: " . $conn->connect_error);
        }
        
        // 设置字符集
        if (!$conn->set_charset(DB_CONFIG['charset'])) {
            throw new Exception("设置字符集失败: " . $conn->error);
        }
        
        // 设置SQL模式
        $conn->query("SET SESSION sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'");
        
        return $conn;
    } catch (Exception $e) {
        error_log("数据库连接错误: " . $e->getMessage());
        throw new Exception("数据库连接错误: " . $e->getMessage());
    }
}

/**
 * 获取系统配置
 * @return array 系统配置数组
 * @throws Exception 获取失败时抛出异常
 */
function getSystemConfig() {
    try {
        $conn = connectDB();
        $conn->begin_transaction();
        
        $sql = "SELECT * FROM configs ORDER BY id DESC LIMIT 1";
        $result = $conn->query($sql);
        
        if (!$result) {
            throw new Exception("获取配置失败: " . $conn->error);
        }
        
        if ($result->num_rows === 0) {
            throw new Exception("未找到系统配置");
        }
        
        $config = $result->fetch_assoc();
        
        // 验证配置有效性
        if (empty($config['phone']) || !preg_match('/^1[3-9]\d{9}$/', $config['phone'])) {
            throw new Exception("无效的电话号码配置");
        }
        
        if ($config['cooldown'] < SYSTEM_CONFIG['min_cooldown'] || 
            $config['cooldown'] > SYSTEM_CONFIG['max_cooldown']) {
            throw new Exception("无效的冷却时间配置");
        }
        
        if (empty($config['default_message'])) {
            throw new Exception("默认消息不能为空");
        }
        
        if (empty($config['app_token']) || empty($config['uid']) || empty($config['api_url'])) {
            throw new Exception("推送配置不完整");
        }
        
        $conn->commit();
        $conn->close();
        
        return $config;
    } catch (Exception $e) {
        if (isset($conn)) {
            $conn->rollback();
            $conn->close();
        }
        error_log("获取系统配置失败: " . $e->getMessage());
        throw new Exception("获取系统配置失败: " . $e->getMessage());
    }
}

/**
 * 获取消息模板
 * @return array 消息模板数组
 * @throws Exception 获取失败时抛出异常
 */
function getMessageTemplates() {
    try {
        $conn = connectDB();
        
        $sql = "SELECT * FROM message_templates WHERE is_active = 1 ORDER BY sort_order ASC";
        $result = $conn->query($sql);
        
        if (!$result) {
            throw new Exception("获取消息模板失败: " . $conn->error);
        }
        
        $templates = [];
        while ($row = $result->fetch_assoc()) {
            if (strlen($row['content']) <= SYSTEM_CONFIG['max_message_length']) {
                $templates[] = $row;
            }
        }
        
        $conn->close();
        
        if (empty($templates)) {
            throw new Exception("未找到有效的消息模板");
        }
        
        return $templates;
    } catch (Exception $e) {
        if (isset($conn)) {
            $conn->close();
        }
        error_log("获取消息模板失败: " . $e->getMessage());
        throw new Exception("获取消息模板失败: " . $e->getMessage());
    }
}

/**
 * 验证数据库连接和表结构
 * @return bool 验证结果
 * @throws Exception 验证失败时抛出异常
 */
function validateDatabase() {
    try {
        $conn = connectDB();
        
        // 检查必要的表是否存在
        $required_tables = ['configs', 'message_templates', 'notifications'];
        foreach ($required_tables as $table) {
            $result = $conn->query("SHOW TABLES LIKE '$table'");
            if ($result->num_rows === 0) {
                throw new Exception("缺少必要的表: $table");
            }
            
            // 检查表结构
            $result = $conn->query("SHOW COLUMNS FROM $table");
            if ($result->num_rows === 0) {
                throw new Exception("表 $table 结构异常");
            }
        }
        
        // 检查事件是否存在
        $result = $conn->query("SHOW EVENTS WHERE Name = 'clean_old_notifications'");
        if ($result->num_rows === 0) {
            throw new Exception("清理历史记录的事件不存在");
        }
        
        $conn->close();
        return true;
    } catch (Exception $e) {
        if (isset($conn)) {
            $conn->close();
        }
        error_log("数据库验证失败: " . $e->getMessage());
        throw new Exception("数据库验证失败: " . $e->getMessage());
    }
}